package excutors;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class CustomRejectedExecutionHandler implements RejectedExecutionHandler {


    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        //0-放入到缓冲队列中
        //1- 将任务放入备用的队列或数据库中
        System.out.println(r.toString() + " is rejected"+Thread.currentThread().getName());
        //2-备用处理逻辑
        //3-信号量限流处理
//        submitTask(r,executor);
        //4进行重试
        submitTaskWithRetry(r, 3, executor);

    }

    Semaphore semaphore = new Semaphore(10);
    public void submitTask(Runnable task,ThreadPoolExecutor executor) {
        try {
            semaphore.acquire();
            executor.submit(() -> {
                try {
                    log.info("任务提交成功{}",Thread.currentThread().getName());
                    task.run();
                } finally {
                    semaphore.release();
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    //重试提交任务
    public void submitTaskWithRetry(Runnable task, int maxRetries, ThreadPoolExecutor executor) {
        int retries = 0;
        while (retries < maxRetries) {
            try {
                executor.submit(task);
                //Main线程
                log.info("任务提交成功{}",Thread.currentThread().getName());
                break; // 任务提交成功，退出循环
            } catch (RejectedExecutionException e) {
                log.error("继续拒绝重试{}{}",retries,
                        Thread.currentThread().getName());
                retries++;
                if (retries >= maxRetries) {
                    // 达到最大重试次数，处理失败逻辑
                    break;
                }
                try {
                    Thread.sleep(1000); // 等待一段时间后重试
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        //信号量限流控制


    }

}
